package com.wox.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

import com.yuchengtech.fileUtil.FileUtil;
import com.yuchengtech.simpleServer.core.SimpleHttpServer;

public abstract class BindResource {

	
	private static HashMap<String,Properties> resourceMap=new HashMap<String, Properties>();
	
	
	/**
	 * 获取配置资源
	 * @param bindId
	 * @return
	 */
	public static Properties getBindProperties(String bindId)
	{
		Properties pro= resourceMap.get(bindId);
		if(pro==null)
		{
			String bindSrc=FileUtil.contactPath(SimpleHttpServer.getBindPath(),bindId+".properties");
			File file=new File(bindSrc);
			if(file.exists()&&file.isFile()&&file.canRead())
			{
				pro=new Properties();
				try {
					pro.load(new FileInputStream(file));
				} catch (Exception e) {
				}
			}
			
		 resourceMap.put(bindId, pro);
		}
		return pro;
	}


	/**
	 * 存储配置文件
	 * @param bindId
	 */
	public static  boolean saveBindProperties(String bindId,Properties pro) {
			if(pro==null)
				{
					pro=resourceMap.get(bindId);
				}else
				{
					resourceMap.put(bindId, pro);
				}
			
			if(pro!=null)
			{
				String bindSrc=FileUtil.contactPath(SimpleHttpServer.getBindPath(),bindId+".properties");
				File file=new File(bindSrc);
				if(!file.exists())
				{
					try {
						file.createNewFile();
					} catch (IOException e) {
						return false;
					}
				}else
				{
					if(!file.isFile()||!file.canRead())
						return false;
				}
				
			  try {
				pro.store(new FileOutputStream(file), "更新配置文件");
			} catch (Exception e) {
					return false;
			}
			}else return false;
			
			
			
			return true;
	}
}
